package com.smart.home.netty.handler;

import com.smart.home.util.CommandEncoder;
import com.smart.home.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 输入信息通道处理抽象类
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-09
 */
public abstract class AbstractChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {
    /**
     * 发送指令内容
     * 该内容组成：设备码 + 十六进制操作码
     */
    private String command;

    /**
     * 返回状态
     * 请求过后需要返回状态时通过该字段实现
     */
    private boolean status;

    /**
     * 返回信息
     * 请求过后需要返回信息时通过该字段实现
     */
    private String message;
    /**
     * 兼容数据传输对象，用于存储特殊数据
     */
    private Object obj;

    /**
     * 按钮名称
     */
    private String buttonName;

    /**
     * 获取编码后的命令集
     *
     * @return
     */
    public byte[] getEncodeCommand() {
        if (StringUtils.isEmpty(command)) {
            return null;
        }
        return CommandEncoder.decode(command);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //连接成功，发送信息
        ctx.writeAndFlush(Unpooled.copiedBuffer(getEncodeCommand()));
    }

    public String getCommand() {
        return command;
    }

    public void setCommand(String command) {
        this.command = command;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getButtonName() {
        return buttonName;
    }

    public void setButtonName(String buttonName) {
        this.buttonName = buttonName;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
}
